package cn.itlight.system.service.impl;

import cn.itlight.basic.service.impl.BaseServiceImpl;
import cn.itlight.system.domain.Role;
import cn.itlight.system.mapper.RoleMapper;
import cn.itlight.system.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tomliu
 * @since 2022-07-11
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;


    @Override
    public void save(Role role) {
        roleMapper.save(role);
        initSaveTable(role);
    }

    /*
    * @Title: initSaveTable
    * @Description: 新增角色初始化菜单权限
    * @Author: TomLiu
    * @Version: 1.0
    * @Date:  2022/7/13 11:46
    * @Parameters:
    * @Return
    */
    private void initSaveTable(Role role) {
        // 判断是否修改菜单
        if (role.getMenus() != null){
            // 在角色菜单中间表新增修改的数据
            roleMapper.saveRoleMenu(role.getId(), role.getMenus());
        }
        // 判断是否修改权限
        if (role.getPermissions() != null){
            // 在角色权限中间表新增修改的数据
            roleMapper.saveRolePermission(role.getId(), role.getPermissions());
        }
    }


    @Override
    public void update(Role role) {
        roleMapper.update(role);
        initRaletionTable(role);
    }

    /*
    * @Title: initRaletionTable
    * @Description: 修改权限菜单初始化
    * @Author: TomLiu
    * @Version: 1.0
    * @Date:  2022/7/13 11:19
    * @Parameters:
    * @Return
    */
    private void initRaletionTable(Role role) {
        // 判断是否修改菜单
        if (role.getMenus() != null){
            // 删除角色菜单中间表的数据
            roleMapper.removeRoleMenu(role.getId());
            // 在角色菜单中间表新增修改的数据
            roleMapper.saveRoleMenu(role.getId(), role.getMenus());
        }
        // 判断是否修改权限
        if (role.getPermissions() != null){
            // 删除角色权限中间表的数据
            roleMapper.removeRolePermission(role.getId());
            // 在角色权限中间表新增修改的数据
            roleMapper.saveRolePermission(role.getId(), role.getPermissions());
        }
    }

    @Override
    public void remove(Long id) {
        initRemoveTable(id);
        roleMapper.remove(id);
    }

    /*
    * @Title: initRemoveTable
    * @Description: 删除角色时删除菜单权限
    * @Author: TomLiu
    * @Version: 1.0
    * @Date:  2022/7/13 11:46
    * @Parameters:
    * @Return
    */
    private void initRemoveTable(Long id) {
        roleMapper.removeRoleMenu(id);
        roleMapper.removeRolePermission(id);
    }
}
